﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Controls;

namespace RiskMan.Config
{
    public class cfg
    {
        public static String Start = "Старт";
        public static String Stop = "Стоп";

        public static readonly string ExecFile = "";

        #region DdeSettings

        public static String DdeServer = "rbkmdde";
        public static string DdeChannelCurrentList = "currentlist";
        public static string DdeChannelDealsList = "deallist";
        public static string DdeChannelLimiteToEmitent = "limitemitentlist";
        public static string DdeChannelPositionToClientAccount = "fortspotitions";
        public static string DdeChannelStopOrders = "stoporders";
        public static string DdeChannelOrders = "orders";
        public static string DdeChannelLimiteByAccount = "limitebyaccount";
        public static string DdeChannelportfel = "portfel";
        public static string DdeLimeiteByCash = "limitebymoneysredstvam";

        #endregion

        public static TimeSpan UpdateStoptableInterval = TimeSpan.FromMilliseconds(500);
        public static TimeSpan UpdateLimitstockInterval = TimeSpan.FromMilliseconds(500);

        public static string ZalogMoney = "Залоговые ден.средства";
        public static string KliringMoney = "Клиринговые ден.средства";
        public static string KliringZalogMoney = "Клиринговые залоговые ден.средства";

        public static String Unknown = "Не выбран";
        public static String StopLimit = "Стоп-лимит";
        public static string TakeProfit = "Тэйк-профит";
        public static string LinkedOrder = "Связанная заявка";
        public static string LinkedOOrder = "Со связ. заявкой";
        public static string StopTakeOrder = "Тэйк-профит и стоп-лимит";
        public static string TakeProfitLimitOrder = "Тейк-профит(Лимит. заявка)";

        public static string Rub = "Рубли";
        public static string ValutPrice = "Валюта цены";
        public static string Persent = "Процентах";


        public static String MainfunctionRm = "Риск менеджер";
        public static String MainfunctionRmInvestor = "Риск менеджер(инвестор)";
        public static String MainfunctionStop = "Стопы";
        public static String MainfunctionLimitstock = "Лимиты по бумагам";
        public static String MainfunctionLimitmoneyanddeals = "Лимиты по деньгам и сделкам";
        public static String MainfunctionScalpStakan = "Скальперский стакан";
        public static string Mainsetting = "Основные";


        public static string Buy = "Купля";
        public static string Sell = "Продажа";

        public static string Active = "Активна";
        public static string Performed = "Исполнена";
        public static string Cancel = "Снята";
        public static string AddToTs = "Выставлена заявка в ТС";
        public static string RemoveFormTs = "Отвергнута ТС";

        public static String Mode0 = "ВМ + НД";
        public static String Mode1 = "ВМ за клиринг";
        public static String Mode2 = "За день(ММВБ)";


        #region Tables

        public static String MainMenuTtp = "Таблица текущих параметров";
        public static String MainMenuStopOrders = "Стоп-заявки";
        public static String MainMenuOrders = "Таблица заявок";
        public static String MainMenuDeals = "Сделки";
        public static String MainMenuPortfel = "Портфель";
        public static String MainMenuLimitByStock = "Лимиты по бумагам";
        public static String MainMenuLimitByCash = "Лимиты по ДС";
        public static String MainMenuLimitByAccountsFuture = "Ограничения по клиентским счетам (фьючерсы)";
        public static String MainMenuLimitByPositionFuture = "Позиции по клиентским счетам (фьючерсы)";

        #endregion

        #region Type Calculation RM

        public static String TypeEnterLimitRmDealTrallingProfit = "Трейлинг прибыль (сделка)";
        public static String TypeEnterLimitRmTrallingProfit = "Трейлинг профит";
        public static String TypeEnterLimitRmCalcRmBasic = "Обычный";
        #endregion

        public static void SetLog(string log, ListBox ListBox_Logs, Type type, MethodBase method)
        {
            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\OptionRobot\\";

                if (!Directory.Exists(path))
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    dir.Create();
                }

                string name = "" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
                using (var file = new StreamWriter(path + name, true))
                    file.WriteLine(DateTime.Now + "   " + log);

                //ListBox_Logs.Items.Add(DateTime.Now + " " + log + " " + type.FullName + "." + method.Name);
                ListBox_Logs.Dispatcher.BeginInvoke(new Action(delegate()
                {
                    ListBox_Logs.Items.Add(DateTime.Now + " " + log);
                    ListBox_Logs.InvalidateVisual();
                    ListBox_Logs.UpdateLayout();
                }));

            }
            catch (Exception)
            {

            }
        }
        public static void SetLog(string log, ListBox ListBox_Logs, Type type, MethodBase method, string tmp)
        {
            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\OptionRobot\\";

                if (!Directory.Exists(path))
                {
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                    dir.Create();
                }

                string name = "" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
                using (var file = new StreamWriter(path + name, true))
                    file.WriteLine(DateTime.Now + "   " + type.FullName + "." + method.Name + " " + log);

                ListBox_Logs.Items.Add(DateTime.Now + "   " + log); // + type.FullName + "." + method.Name + " "

                ListBox_Logs.InvalidateVisual();
                ListBox_Logs.UpdateLayout();
            }
            catch (Exception)
            {

            }
        }

        public static void SetLog(string log, ListBox ListBox_Logs)
        {
            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\OptionRobot\\";

                if (!Directory.Exists(path))
                {
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                    dir.Create();
                }

                string name = "" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
                using (var file = new StreamWriter(path + name, true))
                    file.WriteLine(DateTime.Now + "   " + log);

                ListBox_Logs.Dispatcher.BeginInvoke(new Action(delegate()
                {
                    ListBox_Logs.Items.Add(DateTime.Now + "   " + log); 

                    ListBox_Logs.InvalidateVisual();
                    ListBox_Logs.UpdateLayout();
                }));
            }
            catch (Exception)
            {

            }
        }

        public static void SetLog(string log, Type type, MethodBase method)
        {
            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\OptionRobot\\";

                if (!Directory.Exists(path))
                {
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                    dir.Create();
                }

                string name = "" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + ".txt";
                using (var file = new StreamWriter(path + name, true))
                {
                    file.WriteLine(DateTime.Now + "   " + type.FullName + "." + method.Name + " " + log);
                }
            }
            catch (Exception)
            {

            }
        }
        public static double ToDoubleFormControls(string text)
        {
            try
            {
                if (text.Length == 0)
                    return 0;
                return Convert.ToDouble(text);
            }
            catch (Exception)
            {
                try
                {
                    char ch = '0';
                    for (int i = 0; i < text.Length; i++)
                    {
                        if (text[i] == '.' || text[i] == ',')
                            ch = text[i];
                    }
                    string[] part = text.Split(ch);
                    if (ch == '.')
                        return Convert.ToDouble(part[0] + ',' + part[1]);
                    else return Convert.ToDouble(part[0] + '.' + part[1]);
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }
        public static string SetFormate(int accuracy)
        {
            String result = "{0:0}";
            if (accuracy == 0)
                result = "{0:0}";
            if (accuracy == 1)
                result = "{0:0.0}";
            if (accuracy == 2)
                result = "{0:0.00}";
            if (accuracy == 3)
                result = "{0:0.000}";
            if (accuracy == 4)
                result = "{0:0.0000}";
            if (accuracy == 5)
                result = "{0:0.00000}";
            if (accuracy == 6)
                result = "{0:0.000000}";

            return result;
        }
        public static double getDouble(String frmt, Double pr)
        {
            return Convert.ToDouble(String.Format(frmt, pr));
        }
        public static string GetID()
        {
            string str = "";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor");
            foreach (ManagementObject queryObj in searcher.Get())
                str = queryObj["ProcessorId"].ToString();
            return str;
        }
        public static string GetMacAddress()
        {
            string macAddresses = "";
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    macAddresses += nic.GetPhysicalAddress().ToString();
                    break;
                }
            }
            return macAddresses;
        }
        public static object DeepClone(object obj)
        {
            if (obj == null) { return null; }
            object result = null;
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(ms, obj);
                ms.Position = 0;
                result = bf.Deserialize(ms);
            }
            return result;
        }

        #region Получение списка всех квиков

        public static List<String> getListPathFile()
        {
            List<string> PathFile = new List<string>();
            string[] DriverList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriverList.Length; i++)
            {

                DirectoryInfo di = new DirectoryInfo((DriverList[i]));
                cfg.RecursGetPath(di, "info.exe", PathFile);
            }
            return PathFile;
        }

        static void RecursGetPath(DirectoryInfo predDirec, string findFile, List<string> pathfile)
        {

            FileInfo[] fi;
            try
            {
                fi = predDirec.GetFiles();//Сюда попадут все файлы этой папки
            }
            catch
            {
                return;
            }
            for (int i = 0; i < fi.Length; i++)
            {
                if (fi[i].Name == findFile)
                {
                    pathfile.Add((fi[i].DirectoryName));

                }
            }
            DirectoryInfo[] di = predDirec.GetDirectories();
            for (int i = 0; i < di.Length; i++)
            {
                RecursGetPath(di[i], findFile, pathfile);
            }
        }

        #endregion


    }
}
